package cn.edu.swu.miniwebsvr.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        Parameter parameter = new Parameter();

        // TODO: [2023123456/张三]
        // 1. 读取并解析 HTTP 请求行 (e.g., GET /path?param=value HTTP/1.1)
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) {
            throw new IOException("Empty request");
        }

        String[] requestParts = requestLine.split(" ");
        if (requestParts.length < 2) {
            throw new IOException("Invalid request line: " + requestLine);
        }

        String method = requestParts[0];
        String urlWithParams = requestParts[1];

        parameter.setMethod(method);

        // 解析URL和URL参数
        int queryIndex = urlWithParams.indexOf('?');
        String url;
        Map<String, String> urlParams = new HashMap<>();

        if (queryIndex != -1) {
            url = urlWithParams.substring(0, queryIndex);
            String queryString = urlWithParams.substring(queryIndex + 1);
            parseQueryString(queryString, urlParams);
        } else {
            url = urlWithParams;
        }

        parameter.setUrl(url);
        parameter.setUrlParams(urlParams);

        // 2. 循环读取并解析所有 HTTP 请求头 (e.g., Host: localhost:8080)
        String headerLine;
        while ((headerLine = reader.readLine()) != null) {
            if (headerLine.isEmpty()) {
                break; // 空行表示头部结束
            }

            int colonIndex = headerLine.indexOf(':');
            if (colonIndex > 0) {
                String headerName = headerLine.substring(0, colonIndex).trim();
                String headerValue = headerLine.substring(colonIndex + 1).trim();
                parameter.addHeader(headerName, headerValue);
            }
        }

        // 3. 根据请求方法 (Method) 和请求头 (Content-Length, Content-Type) 判断并读取请求体
        if ("POST".equalsIgnoreCase(method)) {
            String contentLengthStr = parameter.getHeader("Content-Length");
            if (contentLengthStr != null) {
                try {
                    int contentLength = Integer.parseInt(contentLengthStr);
                    if (contentLength > 0) {
                        char[] bodyChars = new char[contentLength];
                        int bytesRead = reader.read(bodyChars, 0, contentLength);
                        if (bytesRead > 0) {
                            String body = new String(bodyChars, 0, bytesRead);
                            String contentType = parameter.getHeader("Content-Type");

                            if (contentType != null && contentType.contains("application/x-www-form-urlencoded")) {
                                parseQueryString(body, parameter.getBodyParams());
                            }
                        }
                    }
                } catch (NumberFormatException e) {
                    System.err.println("Invalid Content-Length: " + contentLengthStr);
                }
            }
        }

        return parameter;
    }

    // TODO: [2023123456/张三] 添加辅助方法来简化字符串解析和 URL 解码
    private static void parseQueryString(String queryString, Map<String, String> params) {
        if (queryString == null || queryString.isEmpty()) {
            return;
        }

        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            int equalsIndex = pair.indexOf('=');
            try {
                if (equalsIndex > 0) {
                    String key = URLDecoder.decode(pair.substring(0, equalsIndex), "UTF-8");
                    String value = URLDecoder.decode(pair.substring(equalsIndex + 1), "UTF-8");
                    params.put(key, value);
                } else if (equalsIndex == -1) {
                    // 只有key没有value的情况
                    String key = URLDecoder.decode(pair, "UTF-8");
                    params.put(key, "");
                }
            } catch (UnsupportedEncodingException e) {
                // UTF-8应该总是可用的
                params.put(pair.substring(0, equalsIndex), pair.substring(equalsIndex + 1));
            }
        }
    }
}